<template>
  <div class="health-record-form">
    <el-form :model="formData" label-width="100px" :rules="rules" ref="formRef">
      <el-form-item label="健康类型" prop="typeId">
        <el-select v-model="formData.typeId" placeholder="请选择健康数据类型" @change="handleTypeChange">
          <el-option
            v-for="type in healthTypes"
            :key="type.id"
            :label="type.name"
            :value="type.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="记录日期" prop="recordDate">
        <el-date-picker
          v-model="formData.recordDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      
      <el-form-item label="记录时间" prop="recordTime">
        <el-time-picker
          v-model="formData.recordTime"
          placeholder="选择时间"
          format="HH:mm:ss"
          value-format="HH:mm:ss"
        />
      </el-form-item>
      
      <el-form-item :label="selectedType ? (selectedType.name + '数值') : '数值'" prop="value" v-if="selectedType && selectedType.isNumeric">
        <el-input
          v-model="formData.value"
          :placeholder="`请输入${selectedType.name}数值${selectedType.unit ? '（' + selectedType.unit + '）' : ''}`"
          clearable
        >
          <template #append v-if="selectedType.unit">
            {{ selectedType.unit }}
          </template>
        </el-input>
        <div class="normal-range" v-if="selectedType.minValue !== null && selectedType.maxValue !== null">
          正常范围：{{ selectedType.minValue }} - {{ selectedType.maxValue }} {{ selectedType.unit }}
        </div>
      </el-form-item>
      
      <el-form-item :label="selectedType ? (selectedType.name + '内容') : '内容'" prop="value" v-if="selectedType && !selectedType.isNumeric">
        <el-input
          v-model="formData.value"
          :placeholder="`请输入${selectedType.name}内容`"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="备注" prop="notes">
        <el-input
          v-model="formData.notes"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
    <div class="form-actions">
      <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
      <el-button @click="resetForm">重置</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 定义事件
const emit = defineEmits(['record-added'])

// 获取当前用户ID
let userId = null
const userInfoStr = localStorage.getItem('userInfo')
const userStr = localStorage.getItem('user')

if (userInfoStr) {
  try {
    userId = JSON.parse(userInfoStr).id
    console.log('从userInfo获取到用户ID:', userId)
  } catch (e) {
    console.error('解析userInfo失败:', e)
  }
} else if (userStr) {
  try {
    userId = JSON.parse(userStr).id
    console.log('从user获取到用户ID:', userId)
  } catch (e) {
    console.error('解析user失败:', e)
  }
}

if (!userId) {
  // 如果都没有获取到，默认使用ID为8用于测试
  userId = 8
  console.log('未找到用户信息，使用默认ID:', userId)
}

// 表单引用
const formRef = ref(null)

// 表单数据
const formData = reactive({
  userId: userId,
  typeId: '',
  value: '',
  recordDate: new Date().toISOString().split('T')[0], // 默认为今天
  recordTime: new Date().toTimeString().split(' ')[0].substring(0, 8), // 默认为当前时间
  notes: ''
})

// 表单验证规则
const rules = {
  typeId: [{ required: true, message: '请选择健康数据类型', trigger: 'change' }],
  value: [{ required: true, message: '请输入数值', trigger: 'blur' }],
  recordDate: [{ required: true, message: '请选择记录日期', trigger: 'change' }],
  recordTime: [{ required: true, message: '请选择记录时间', trigger: 'change' }]
}

// 健康类型列表
const healthTypes = ref([])
const submitting = ref(false)

// 获取选中的健康类型
const selectedType = computed(() => {
  return healthTypes.value.find(type => type.id === formData.typeId) || null
})

// 类型变化时重置部分表单数据
const handleTypeChange = () => {
  formData.value = ''
}

// 获取健康记录类型
const getHealthTypes = async () => {
  try {
    // 尝试从本地存储获取数据
    const localData = localStorage.getItem('health_types')
    if (localData) {
      healthTypes.value = JSON.parse(localData)
      console.log('从本地存储加载健康类型:', healthTypes.value)
      return
    }
    
    // 使用模拟数据
    loadDemoTypes()
    
    // 保存演示数据到本地存储
    localStorage.setItem('health_types', JSON.stringify(healthTypes.value))
  } catch (error) {
    console.error('获取健康记录类型失败', error)
    // 加载演示数据
    loadDemoTypes()
    // 保存演示数据到本地存储
    localStorage.setItem('health_types', JSON.stringify(healthTypes.value))
  }
}

// 加载演示的健康类型数据
const loadDemoTypes = () => {
  healthTypes.value = [
    { id: 1, name: '血压(收缩压)', unit: 'mmHg', isNumeric: true, minValue: 60, maxValue: 180, icon: 'iconfont icon-blood-pressure' },
    { id: 2, name: '血压(舒张压)', unit: 'mmHg', isNumeric: true, minValue: 40, maxValue: 120, icon: 'iconfont icon-blood-pressure' },
    { id: 3, name: '心率', unit: '次/分钟', isNumeric: true, minValue: 40, maxValue: 200, icon: 'iconfont icon-heart-rate' },
    { id: 4, name: '血糖(空腹)', unit: 'mmol/L', isNumeric: true, minValue: 3.9, maxValue: 6.1, icon: 'iconfont icon-blood-glucose' },
    { id: 5, name: '血糖(餐后2小时)', unit: 'mmol/L', isNumeric: true, minValue: 3.9, maxValue: 7.8, icon: 'iconfont icon-blood-glucose' },
    { id: 6, name: '体重', unit: 'kg', isNumeric: true, minValue: 30, maxValue: 150, icon: 'iconfont icon-weight' },
    { id: 7, name: '体温', unit: '℃', isNumeric: true, minValue: 35, maxValue: 42, icon: 'iconfont icon-temperature' },
    { id: 8, name: '睡眠时间', unit: '小时', isNumeric: true, minValue: 0, maxValue: 24, icon: 'iconfont icon-sleep' },
    { id: 9, name: '用药记录', unit: '', isNumeric: false, minValue: null, maxValue: null, icon: 'iconfont icon-medication' },
    { id: 10, name: '饮食记录', unit: '', isNumeric: false, minValue: null, maxValue: null, icon: 'iconfont icon-diet' }
  ]
}

// 英文健康类型名称翻译为中文
const translateTypeName = (engName) => {
  const typeMap = {
    'Blood Pressure (Systolic)': '血压(收缩压)',
    'Blood Pressure (Diastolic)': '血压(舒张压)',
    'Heart Rate': '心率',
    'Blood Glucose (Fasting)': '血糖(空腹)',
    'Blood Glucose (2h Postprandial)': '血糖(餐后2小时)',
    'Weight': '体重',
    'Body Temperature': '体温',
    'Sleep Duration': '睡眠时间',
    'Medication Record': '用药记录',
    'Dietary Record': '饮食记录'
  }
  return typeMap[engName] || engName
}

// 英文健康类型描述翻译为中文
const translateTypeDescription = (engDesc) => {
  const descMap = {
    'Systolic blood pressure measurement': '收缩压测量',
    'Diastolic blood pressure measurement': '舒张压测量',
    'Heart rate measurement': '心率测量',
    'Fasting blood glucose level': '空腹血糖水平',
    'Blood glucose 2 hours after meal': '餐后2小时血糖水平',
    'Body weight measurement': '体重测量',
    'Body temperature measurement': '体温测量',
    'Hours of sleep per night': '每晚睡眠时间',
    'Daily medication intake records': '每日药物摄入记录',
    'Daily food intake records': '每日食物摄入记录'
  }
  return descMap[engDesc] || engDesc
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    if (!formData.typeId) {
      ElMessage.warning('请选择健康记录类型')
      return
    }
    
    const selectedType = healthTypes.value.find(t => t.id === formData.typeId)
    
    // 检查数值健康记录是否符合范围
    if (selectedType.isNumeric) {
      if (!formData.value) {
        ElMessage.warning(`请输入${selectedType.name}数值`)
        return
      }
      
      const numValue = parseFloat(formData.value)
      if (isNaN(numValue)) {
        ElMessage.warning(`${selectedType.name}数值必须是数字`)
        return
      }
      
      if (selectedType.minValue !== null && numValue < selectedType.minValue) {
        ElMessage.warning(`${selectedType.name}数值不能小于${selectedType.minValue}${selectedType.unit}`)
        return
      }
      
      if (selectedType.maxValue !== null && numValue > selectedType.maxValue) {
        ElMessage.warning(`${selectedType.name}数值不能大于${selectedType.maxValue}${selectedType.unit}`)
        return
      }
    } else if (!formData.value && !formData.notes) {
      // 非数值类型记录，至少要有记录内容或备注
      ElMessage.warning(`请输入${selectedType.name}内容或备注`)
      return
    }
    
    try {
      submitting.value = true
      
      // 从本地存储获取现有健康记录
      let healthRecords = []
      const localData = localStorage.getItem(`health_records_${userId}`)
      if (localData) {
        healthRecords = JSON.parse(localData)
      }
      
      // 准备新记录
      const isAbnormal = selectedType.isNumeric && 
        (parseFloat(formData.value) < selectedType.minValue || 
         parseFloat(formData.value) > selectedType.maxValue)
      
      const newRecord = {
        id: Date.now(), // 使用时间戳作为唯一ID
        userId: userId,
        typeId: formData.typeId,
        recordValue: formData.value,
        recordDate: formData.recordDate,
        recordTime: formData.recordTime,
        notes: formData.notes,
        typeName: selectedType.name,
        unit: selectedType.unit,
        isAbnormal: isAbnormal,
        createTime: new Date().toISOString()
      }
      
      // 添加新记录
      healthRecords.unshift(newRecord)
      
      // 保存到本地存储
      localStorage.setItem(`health_records_${userId}`, JSON.stringify(healthRecords))
      
      // 更新健康总览数据
      updateHealthOverview(newRecord)
      
      ElMessage.success('健康记录添加成功')
      emit('record-added')
      // 重置表单
      resetForm()
    } catch (error) {
      console.error('添加健康记录失败', error)
      ElMessage.error('添加健康记录失败')
    } finally {
      submitting.value = false
    }
  })
}

// 更新健康总览数据
const updateHealthOverview = (newRecord) => {
  // 从本地存储获取健康总览数据
  let overviewData = []
  const localData = localStorage.getItem(`health_overview_${userId}`)
  if (localData) {
    overviewData = JSON.parse(localData)
  }
  
  // 查找是否已存在该类型的记录
  const existingIndex = overviewData.findIndex(item => item.typeId === newRecord.typeId)
  
  const selectedType = healthTypes.value.find(t => t.id === newRecord.typeId)
  const overviewItem = {
    typeId: newRecord.typeId,
    typeName: selectedType.name,
    lastValue: newRecord.recordValue,
    unit: selectedType.unit,
    lastDate: `${newRecord.recordDate} ${newRecord.recordTime}`,
    isAbnormal: newRecord.isAbnormal
  }
  
  if (existingIndex >= 0) {
    // 更新现有记录
    overviewData[existingIndex] = overviewItem
  } else {
    // 添加新记录
    overviewData.push(overviewItem)
  }
  
  // 保存更新后的总览数据
  localStorage.setItem(`health_overview_${userId}`, JSON.stringify(overviewData))
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.typeId = ''
  formData.value = ''
  formData.notes = ''
  formData.recordDate = new Date().toISOString().split('T')[0]
  formData.recordTime = new Date().toTimeString().split(' ')[0].substring(0, 8)
}

// 初始化
onMounted(() => {
  getHealthTypes()
})
</script>

<style scoped>
.health-record-form {
  padding: 10px;
}

.normal-range {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.form-actions {
  text-align: right;
  margin-top: 20px;
}
</style> 